<template>
  <d2-container>
    <template slot="header">
      <el-form
        :inline="true"
        :model="queryForm"
        ref="queryForm"
        size="mini"
        style="margin-bottom: -18px;"
      >
        <el-form-item prop="filterType">
          <el-select v-model="queryForm.filterType" placeholder="请输入" style="width: 100px;">
            <el-option
              v-for="(item, index) in queryForm.selection"
              :key="index"
              :label="item.valueName"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="filterValue">
          <el-input v-model="queryForm.filterValue" placeholder="请输入" style="width: 100px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFormSubmit">
            <d2-icon name="search" />查询
          </el-button>
        </el-form-item>
      </el-form>
    </template>
    <split-pane :min-percent="10" :max-percent="20" :default-percent="20" split="vertical">
      <template slot="paneL">
        <h3>设备型号</h3>
        <my-instruction-tree @change="onAreaChange" />
      </template>
      <template slot="paneR">
        <d2-crud
          ref="d2Crud"
          :columns="columns"
          :data="data"
          :loading="loading"
          :pagination="pagination"
          @pagination-current-change="paginationCurrentChange"
          @dialog-open="handleDialogOpen"
          @dialog-cancel="handleDialogCancel"
          :form-options="formOptions"
          add-title="新增定时任务"
          :add-template="addTemplate"
          :add-rules="addRules"
          @row-add="handleRowAdd"
          :rowHandle="rowHandle"
          edit-title="修改定时任务"
          :edit-template="addTemplate"
          :edit-rules="addRules"
          @row-edit="handleRowEdit"
          @row-remove="handleRowRemove"
          @form-data-change="handleFormDataChange"
        >
          <el-button size="mini" slot="header" style="margin-bottom: 5px" @click="addRow">新增</el-button>
        </d2-crud>
      </template>
    </split-pane>
  </d2-container>
</template>

<script>
import util from "@/libs/util";
import MyInstructionTree from "@/components/my-instruction-tree";
import { Divider } from "element-ui";

export default {
  name: "instruction",
  components: { MyInstructionTree },

  data() {
    return {
      loading: false,
      pagination: {
        currentPage: 1,
        pageSize: 100,
        total: 0
      },
      queryForm: {
        equipmentId: "",
        equipmentName: "",
        filterValue: "",
        selection: [],
        filterType: ""
      },
      columns: [
        {
          title: "序号",
          key: "serialNum",
          width: 50
        },
        {
          title: "任务名称",
          key: "name",
          sortable: true
        },
        {
          title: "设备型号",
          key: "equipmentIdName",
          sortable: true
        },
        {
          title: "集中器",
          key: "equipConcents",
          sortable: true
        },
        {
          title: "执行频率",
          key: "treeIdName",
          sortable: true
        },
        {
          title: "定时规则",
          key: "timeCron",
          sortable: true
        }
      ],
      data: [],
      treeData: [],
      values: [],
      selectParams: {
        size: "mini"
      },
      rowHandle: {
        columnHeader: "操作",
        edit: {
          text: "编辑"
        },
        remove: {
          text: "删除"
        }
      },

      selectionRow: [],
      treeParams: {
        "default-expand-all": true,
        data: [],
        props: {
          children: "children",
          label: "name",
          value: "id"
        }
      },
      formOptions: {
        labelWidth: "150px",
        labelPosition: "left",
        saveLoading: false
      },
      addTemplate: {
        id: {
          title: "id",
          value: "",
          component: {
            show: false
          }
        },
        equipmentId: {
          title: "equipmentId",
          value: "",
          component: {
            show: false
          }
        },
        equipmentName: {
          title: "设备型号",
          value: "",
          component: {
            disabled: true
          }
        },
        equipConcents: {
          title: "集中器列表",
          value: [],
          component: {
            name: "el-select",
            multiple: true,
            options: []
          }
        },
        taskId: {
          title: "指令类型",
          value: [],
          component: {
            name: "el-select",
            options: []
          }
        },
        treeId: {
          title: "定时任务发生频率",
          value: "",
          component: {
            name: "el-select",
            options: []
          }
        },
        timeCron: {
          title: "定时规则",
          value: "",
          component: {
            show: false
          }
        },
        day: {
          title: "日",
          value: 1,
          component: {
            name: "el-select",
            options: [],
            show: false
          }
        },
        week: {
          title: "周",
          value: 1,
          component: {
            name: "el-select",
            options: [],
            show: false
          }
        },
        hour: {
          title: "时",
          value: 1,
          component: {
            name: "el-select",
            options: [],
            show: false
          }
        },
        minute: {
          title: "分",
          value: 1,
          component: {
            name: "el-select",
            options: [],
            show: false
          }
        }
      },
      addRules: {
        equipConcents: [{ required: true, message: "必填", trigger: "blur" }],
        taskId: [{ required: true, message: "必填", trigger: "blur" }],
        treeId: [{ required: true, message: "必填", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.getEquipmentType();
    this.initData();
    //获取集中器
    this.getConcent();
    //初始化频率
    this.initFrequency();
  },

  methods: {
    //监听表单变化
    handleFormDataChange({ key, value }) {
      //0 一次 日时分； 1 每时 分,2 每日 时分 ，3 每周 周时分, 4每月 日时分
      if (key == "treeId") {
        this.addTemplate.day.component.show = false;
        this.addTemplate.week.component.show = false;
        this.addTemplate.hour.component.show = false;
        this.addTemplate.minute.component.show = false;
        if (value == 0) {
          this.addTemplate.day.component.show = true;
          this.addTemplate.hour.component.show = true;
          this.addTemplate.minute.component.show = true;
        } else if (value == 1) {
          this.addTemplate.minute.component.show = true;
        } else if (value == 2) {
          this.addTemplate.hour.component.show = true;
          this.addTemplate.minute.component.show = true;
        } else if (value == 3) {
          this.addTemplate.week.component.show = true;
          this.addTemplate.hour.component.show = true;
          this.addTemplate.minute.component.show = true;
        } else {
          this.addTemplate.day.component.show = true;
          this.addTemplate.hour.component.show = true;
          this.addTemplate.minute.component.show = true;
        }
      }
    },
    //初始化频率
    initFrequency() {
      //初始化日
      let dayList = [];
      for (let i = 1; i <= 27; i++) {
        let dayObj = {
          value: i,
          label: i
        };
        dayList.push(dayObj);
      }
      this.addTemplate.day.component.options = dayList;
      //初始化周
      let weekList = [];
      for (let i = 1; i <= 7; i++) {
        let weekObj = {
          value: i+'',
          label: "周" + i
        };
        weekList.push(weekObj);
      }
      this.addTemplate.week.component.options = weekList;
      //初始化周
      let hourList = [];
      for (let i = 0; i <= 23; i++) {
        let hourObj = {
          value: i,
          label: i
        };
        hourList.push(hourObj);
      }
      this.addTemplate.hour.component.options = hourList;
      //初始化分
      let minuteList = [];
      for (let i = 0; i <= 59; i++) {
        let minuteObj = {
          value: i,
          label: i
        };
        minuteList.push(minuteObj);
      }
      this.addTemplate.minute.component.options = minuteList;
    },
    //获取设备指令
    getInstruction() {
      this.$api
        .admin_instruction_getList({
          equipmentId: this.queryForm.equipmentId
        })
        .then(res => {
          let equipmentTypeOptions = res.map(i => {
            return {
              value: i.id,
              label: i.treeName
            };
          });
          this.addTemplate.taskId.component.options = equipmentTypeOptions;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    //获取集中器列表
    getConcent() {
      this.$api
        .admin_concent_getList({
          areaOrg: "1"
        })
        .then(res => {
          let concentOptions = res.map(i => {
            return {
              value: i.id + "",
              label: i.conncentName
            };
          });
          this.addTemplate.equipConcents.component.options = concentOptions;
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    handleDialogOpen({ mode, row, index }) {
      if (mode === "edit") {
        this.$api.admin_task_get({ id: row.id }).then(res => {
          let templateObj = {};
          templateObj.equipConcents = res.equipConcents.split(",");
          templateObj.equipmentId = res.equipmentId;
          templateObj.equipmentName = this.queryForm.equipmentName;
          templateObj.id = res.id;
          templateObj.taskId = res.taskId;
          templateObj.timeCron = res.timeCron;
          console.log(res.timeCron.split(","));
          templateObj.day = Number(res.timeCron.split(",")[0]);
          templateObj.hour = res.timeCron.split(",")[1];
          templateObj.minute = res.timeCron.split(",")[2];
          templateObj.week = res.timeCron.split(",")[3];
          templateObj.treeId = res.treeId;

          this.$refs.d2Crud.setFormData(templateObj);
          if (res.treeId == 0) {
            this.addTemplate.day.component.show = true;
            this.addTemplate.week.component.show = false;
            this.addTemplate.hour.component.show = true;
            this.addTemplate.minute.component.show = true;
          } else if (res.treeId == 1) {
            this.addTemplate.day.component.show = false;
            this.addTemplate.week.component.show = false;
            this.addTemplate.hour.component.show = false;
            this.addTemplate.minute.component.show = true;
          } else if (res.treeId == 2) {
            this.addTemplate.day.component.show = false;
            this.addTemplate.week.component.show = false;
            this.addTemplate.hour.component.show = true;
            this.addTemplate.minute.component.show = true;
          } else if (res.treeId == 3) {
            this.addTemplate.day.component.show = false;
            this.addTemplate.week.component.show = true;
            this.addTemplate.hour.component.show = true;
            this.addTemplate.minute.component.show = true;
          } else if (res.treeId == 4) {
            this.addTemplate.day.component.show = true;
            this.addTemplate.week.component.show = false;
            this.addTemplate.hour.component.show = true;
            this.addTemplate.minute.component.show = true;
          }
        });
      }
    },
    //删除row数据
    handleRowRemove({ index, row }, done) {
      this.$api.admin_task_delete([row.id]).then(res => {
        this.$message({
          message: "删除成功",
          type: "success"
        });
        this.fetchData();
        done();
      });
    },
    //增加row数据
    handleRowEdit({ row }, done) {
      this.formOptions.saveLoading = true;
      let timeCronList = [];
      let { treeId, day, hour, minute, week } = row;
      timeCronList =
        row.treeId == 0
          ? [day, hour, minute, ""]
          : row.treeId == 1
          ? ["", "", minute, ""]
          : row.treeId == 2
          ? ["", hour, minute, ""]
          : row.treeId == 3
          ? ["", hour, minute, week]
          : [day, hour, minute, ""];
      console.log(row);
      let saveObj = {
        id: row.id,
        equipConcents: row.equipConcents.toString(),
        equipmentId: row.equipmentId,
        taskId: row.taskId,
        treeId: row.treeId,
        timeCron: timeCronList.toString()
      };
      this.$api
        .admin_task_update(saveObj)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    //关闭弹框
    handleDialogCancel(done) {
      done();
    },
    //新增数据
    addRow() {
      this.$refs.d2Crud.showDialog({
        mode: "add"
      });
      let templateObj = {};
      templateObj.equipConcents = "";
      templateObj.equipmentId = this.queryForm.equipmentId;
      templateObj.equipmentName = this.queryForm.equipmentName;
      templateObj.id = "";
      templateObj.taskId = "";
      templateObj.timeCron = "";
      templateObj.treeId = "";
      templateObj.day = 1;
      templateObj.hour = 1;
      templateObj.minute = 1;
      templateObj.week = 1;
      this.$refs.d2Crud.setFormData(templateObj);
      this.addTemplate.day.component.show = false;
      this.addTemplate.week.component.show = false;
      this.addTemplate.hour.component.show = false;
      this.addTemplate.minute.component.show = false;
    },
    handleRowAdd(row, done) {
      this.formOptions.saveLoading = true;
      row.equipmentId = this.queryForm.equipmentId;
      let timeCronList = [];
      let { treeId, day, hour, minute, week } = row;
      timeCronList =
        row.treeId == 0
          ? [day, hour, minute, ""]
          : row.treeId == 1
          ? ["", "", minute, ""]
          : row.treeId == 2
          ? ["", hour, minute, ""]
          : row.treeId == 3
          ? ["", hour, minute, week]
          : [day, hour, minute, ""];
      let saveObj = {
        id: row.id,
        equipConcents: row.equipConcents.toString(),
        equipmentId: row.equipmentId,
        taskId: row.taskId,
        treeId: row.treeId,
        timeCron: timeCronList.toString()
      };

      this.$api
        .admin_task_add(saveObj)
        .then(res => {
          this.$message({
            message: "保存成功",
            type: "success"
          });
          this.handleFormSubmit();
          done();
        })
        .finally(() => {
          this.formOptions.saveLoading = false;
        });
    },
    //获取查询枚举
    getEquipmentType() {
      this.$api
        .admin_task_getEquipmentType()
        .then(res => {
          console.log(res);
          this.queryForm.selection = res.sysconfigTask;
          let equipmentTypeOptions = res.treeNameEnum.map(i => {
            return {
              value: i.value,
              label: i.valueName
            };
          });
          this.addTemplate.treeId.component.options = equipmentTypeOptions;
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {});
    },
    //分页操作
    paginationCurrentChange(currentPage) {
      this.pagination.currentPage = currentPage;
      this.fetchData();
    },
    onAreaChange(data, node) {
      this.queryForm.equipmentId = data.id;
      this.queryForm.equipmentName = data.name;
      this.handleFormSubmit();
    },
    initData() {
      this.$api;
      this.$api.admin_equipmentmodel_getList().then(res => {
        this.queryForm.equipmentId = res[0].id;
        this.queryForm.equipmentName = res[0].name;
        this.handleFormSubmit();
      });
    },
    fetchData() {
      this.loading = true;
      this.$api
        .admin_task_getPageList({
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          equipId: this.queryForm.equipmentId,
          filterType: this.queryForm.filterType,
          filterValue: this.queryForm.filterValue
        })
        .then(res => {
          // res.data.forEach(element => {
          //   let txtList = element.timeCron.split(',');
          //   element.timeCronTxt = element.treeId == 0
          //     ? `${txtList[0]}日${txtList[1]}时${txtList[2]}分`
          //     : element.treeId == 1
          //     ? `${txtList[2]}分`
          //     : element.treeId == 2
          //     ? `${txtList[1]}时${txtList[2]}分`
          //     : element.treeId == 3
          //     ? `周${txtList[3]}${txtList[1]}时${txtList[2]}分`
          //     : `${txtList[0]}日${txtList[1]}时${txtList[2]}分`;
          // });
          this.data = res.data;
          this.pagination.total = res.total;
          this.getInstruction();
        })
        .catch(err => {
          console.log("err", err);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleFormSubmit() {
      this.pagination.currentPage = 1;
      this.fetchData();
    }
  }
};
</script>
